class AfterService < ActiveRecord::Base
  include DynamicDefaultScoping

  validates :order_item_id,
    :presence => true
  
  belongs_to :order_item
  has_many :feeds, :dependent => :destroy, :order => 'position asc'
  belongs_to :feed
  belongs_to :updated_by_user, :class_name => 'User', :foreign_key => :updated_by_user_id

  default_scope :current_enterprise,lambda {where(:enterprise_id => Enterprise.current_id )}
  scope :has_been_sent_to_after_service, lambda{where( 'feeds.type in (?)',['Feed::AfterServiceCreated']).includes(:feed)}  

  after_create do |after_service|
    after_service.update_attribute :feed, Feed::AfterServiceCreated.create!(
      :order_item_id => after_service.order_item_id,
      :after_service_id => after_service.id)
  end

  before_save do |after_service|
    after_service.updated_by_user_id = User.current_id if after_service.changed?
  end
  
  after_update do |after_service|
    after_service.order_item.reset_after_serviced_cost!
  end

  after_save do |after_service|
    after_service.order_item.order.update_attribute(:after_serviced_on, after_service.after_serviced_on) if after_service.order_item.order.after_serviced_on.nil? or after_service.order_item.order.after_serviced_on < after_service.after_serviced_on
    after_service.order_item.order.reset_gathered_balance!
  end
  
  after_destroy do |after_service|
    after_service.order_item.order.reset_gathered_balance!
  end

  def self.gathered_balance(order_id)
    where('order_items.order_id = ?', order_id).includes(:order_item).sum(:gathered_balance)
  end

  def can_destroy?
    feeds.each do |feed|
      if feed.is_a?(Feed::AfterServiceFinished) || feed.is_a?(Feed::AfterServiceUnfinished)
        return false
      end
    end
    return true
  end

  # 设置状态为 售后完成
  def finished!
    update_attributes :feed => Feed::AfterServiceFinished.create!(
        :order_item_id => order_item.id,
        :after_service_id => id)
  end

  # 设置状态为 安装完成
  def unfinished!
    update_attributes :feed => Feed::AfterServiceUnfinished.create!(
        :order_item_id => order_item.id,
        :after_service_id => id)
  end

  def update_gathered_balance!
      update_attribute :gathered_balance, 0
  end
  
  def reset_feed!
    update_attributes :feed_id => Feed.where(:after_service_id => id).last.try(:id)
  end
end
